package com.ciwong.epaper.widget;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.oralevaluate.bean.SubWord;
import com.ciwong.libs.oralevaluate.bean.Word;

import java.util.List;

import static com.ciwong.epaper.util.FeedbackUtil.FEEDBACK_TYPE_SYMBOL;

public class ColorationTextView extends android.support.v7.widget.AppCompatTextView {
    private static final String TAG = "PartColorTextView";

    public ColorationTextView(Context context) {
        this(context, null);
    }

    public ColorationTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ColorationTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    private void setSymbolColorationByHtml(EvaluateResult evaluateResult) {
        if (evaluateResult == null) {
            return;
        }
        boolean isSomeSubWordsNull = false;
        StringBuilder stringBuilder = new StringBuilder();
        List<Word> words = evaluateResult.getWords();
        if (words != null && words.size() > 0) {
            for (int i = 0; i < words.size(); i++) {
                Word word = words.get(i);
                if (word.getType() == 4 && "sil".equals(word.getText())) {
                    continue;
                }
                if (word.getType() == 7 || word.getSubwords().size() == 0) {
                    continue;
                }
                if (!stringBuilder.toString().contains("[")) {
                    stringBuilder.append("[");
                } else {
                    stringBuilder.append(" ");
                }
                List<SubWord> subwords = word.getSubwords();
                if (subwords != null && subwords.size() > 0) {
                    for (int j = 0; j < subwords.size(); j++) {
                        SubWord subWord = subwords.get(j);
                        String htmlFormatSymbol = getHtmlFormatSymbol(subWord);
//                        Log.e(TAG, "setSymbolColorationByHtml: "+htmlFormatSymbol );
                        stringBuilder.append(htmlFormatSymbol);
                    }
                } else {
                    String s = JsonParserUtil.toJson(evaluateResult);
                    if (!TextUtils.isEmpty(s)) {
                        FeedbackUtil.getInstance().addFeedbackLog(FEEDBACK_TYPE_SYMBOL, s, "EvaluateResult中的subwords返回null");
                    }
                    isSomeSubWordsNull = true;
                }
            }
        }
        if (isSomeSubWordsNull) {
            return;
        } else {

            stringBuilder.append("]");
        }

        if (!TextUtils.isEmpty(stringBuilder.toString())) {
            setText(Html.fromHtml(stringBuilder.toString()));
        }

    }

    public String getHtmlFormatSymbol(SubWord subWord) {
        StringBuilder stringBuilder = new StringBuilder();
        if (subWord.getScore() <= 6) {
            stringBuilder.append("<font color='#E5220E'>").append(subWord.getSubtext()).append("</font>");
        } else if ((subWord.getScore() <= 8)) {
            stringBuilder.append("<font color='#FFA800'>").append(subWord.getSubtext()).append("</font>");
        } else {
            stringBuilder.append("<font color='#1BC423'>").append(subWord.getSubtext()).append("</font>");
        }
        return stringBuilder.toString();
    }

    public void setSymbolColoration(EvaluateResult evaluateResult, String orginalSymbol) {
        setSymbolColoration(evaluateResult, orginalSymbol, false);
    }

    //orginalSymbol如果为"",表明染色控件与音标控件为同一个，此时如果symbol为Empty,不处理直接显示原来的音标
    public void setSymbolColoration(EvaluateResult evaluateResult, String orginalSymbol, boolean isAddOrignalSymbol) {
        try {
            String symbol = getCompleteReturnSymbol(evaluateResult);
//            Log.e(TAG, "setSymbolColoration subWordText symbol: "+symbol);
            if (TextUtils.isEmpty(symbol)) {
                if (TextUtils.isEmpty(orginalSymbol) || "[-]".equals(orginalSymbol)) {
                    if (isAddOrignalSymbol) {
                        setText(orginalSymbol);
                    } else {
                        return;
                    }

                }
                if (!TextUtils.isEmpty(orginalSymbol) && orginalSymbol.length() > 2) {
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(orginalSymbol);
                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#E5220E"));
                    int start = orginalSymbol.indexOf("[");
                    spannableStringBuilder.setSpan(foregroundColorSpan, start + 1, orginalSymbol.length() - 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    setText(spannableStringBuilder);
                }
                return;
            }

            SpannableStringBuilder builder = new SpannableStringBuilder(symbol);
            List<Word> words = evaluateResult.getWords();
            int index = 0;
            if (words != null && words.size() > 0) {
                for (int i = 0; i < words.size(); i++) {
                    Word word = words.get(i);
                    List<SubWord> subwords = word.getSubwords();
                    if (subwords != null && subwords.size() > 0) {
                        for (int j = 0; j < subwords.size(); j++) {
                            SubWord subWord = subwords.get(j);
                            String subWordText = subWord.getSubtext();
                            int start = symbol.indexOf(subWordText, index);
                            int end = start + subWordText.length();
                            if (EApplication.isIngnorAccent && isIngore(subWordText)) {
                                int color = Color.parseColor("#7e8883");
                                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(color);
                                builder.setSpan(foregroundColorSpan, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                            } else {
                                builder.setSpan(SpeechUtils.getForegroundColorSpanByScore(subWord), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                            }

                            index = end;
                        }
                    }

                }
            }
//            Log.e(TAG, "setSymbolColoration: builder ------------------------------- " +builder);
            if (!TextUtils.isEmpty(builder)) {
                setText(builder);
            }
        } catch (Exception e) {

        }
    }

    public void setSymbolText(EvaluateResult evaluateResult, String orginalSymbol) {
        try {
            String symbol = getCompleteReturnSymbol(evaluateResult);
            if (TextUtils.isEmpty(symbol)) {
                if (TextUtils.isEmpty(orginalSymbol) || "[-]".equals(orginalSymbol)) {
                    setText(orginalSymbol);
                }
            } else {
                setText(symbol);
            }
        } catch (Exception e) {

        }
    }

    private boolean isIngore(String subWordText) {
        if ("'".equals(subWordText)) {
            return true;
        }
        if (",".equals(subWordText)) {
            return true;
        }
        if ("ˌ".equals(subWordText)) {
            return true;
        }
        return false;
    }


    @NonNull
    private String getCompleteReturnSymbol(EvaluateResult evaluateResult) {
        if (evaluateResult == null) {
            return "";
        }
        boolean isSomeSubWordsNull = false;
        List<Word> words = evaluateResult.getWords();
        StringBuilder stringBuilder = new StringBuilder();
        if (words != null && words.size() > 0) {
            for (int i = 0; i < words.size(); i++) {
                Word word = words.get(i);
                if (word.getType() == 4 && "sil".equals(word.getText())) {
                    continue;
                }
                if (word.getType() == 7 || word.getSubwords().size() == 0) {
                    continue;
                }
                if (!stringBuilder.toString().contains("[")) {
                    stringBuilder.append("[");
                } else {
                    stringBuilder.append(" ");
                }
                List<SubWord> subwords = word.getSubwords();
                if (subwords != null && subwords.size() > 0) {

                    for (int j = 0; j < subwords.size(); j++) {
                        SubWord subWord = subwords.get(j);
                        stringBuilder.append(subWord.getSubtext());
                    }

                } else {
                    String s = JsonParserUtil.toJson(evaluateResult);
                    if (!TextUtils.isEmpty(s)) {
                        FeedbackUtil.getInstance().addFeedbackLog(FEEDBACK_TYPE_SYMBOL, s, "EvaluateResult中的subwords返回null");
                    }
                    isSomeSubWordsNull = true;
                }

            }
        }
        stringBuilder.append("]");
        String symbol = stringBuilder.toString();
        if (isSomeSubWordsNull) {
            return "";
        } else {
            return symbol;
        }

    }


}  